package com.odontosis.view.login;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.odontosis.entidade.Usuario;
import com.odontosis.service.UsuarioService;
import com.odontosis.view.OdontosisAction;
/**
 * Acao para o login de usuario
 * 
 * @author pablo
 *
 */
public class AcaoLogin extends OdontosisAction<UsuarioService> {
	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception {
		FormLogin formulario = (FormLogin) form;
		if(StringUtils.isEmpty(formulario.getMetodo()))
		{
			return onIniciarTela(mapping, form, request, response);
		}
		return onLogar(mapping, form, request, response);
	}
	
	
	public ActionForward onIniciarTela(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception {
		if(request.getSession().getAttribute("usuario") != null){
			return mapping.findForward("principal");
		}
		return mapping.getInputForward();
	}
	
	public ActionForward onLogar(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception {
		FormLogin formulario = (FormLogin) form;
		Usuario usuario = service.buscarPorLogin(formulario.getLogin());
		if(usuario != null && usuario.getSenha().equals(formulario.getSenha())){
			request.getSession().setAttribute("usuario", usuario); 
			return mapping.findForward("principal");
		}
		return mapping.getInputForward();
	}

}
